package cn.zhaopin.starter.security.convert;

import cn.zhaopin.starter.security.common.SecurityConstant;
import cn.zhaopin.starter.security.token.WeWorkThirdAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Description: 企业微信认证token转换
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2021/10/08-13:33
 */
@Slf4j
public class WeworkThirdAuthenticationConverter extends BasicAuthenticationConverter {

    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();

        //设置路径缓存
        holderPathValue(request.getPath().value());

        //封装未认证的token
        String code = obtainQueryFirst(request, SecurityConstant.PARAMETER.LOGIN_CODE);
        String suiteId = obtainQueryFirst(request, SecurityConstant.PARAMETER.LOGIN_SUITE_ID);
        String loginType = obtainQueryFirst(request, SecurityConstant.PARAMETER.LOGIN_TYPE);
        loginType = StringUtils.hasLength(loginType) ? loginType : SecurityConstant.LOGIN_TYPE.WEWORK_THIRD_WEB;
        String state = obtainQueryFirst(request, SecurityConstant.PARAMETER.LOGIN_STATE);
        argsCheck(code, suiteId, loginType, state);
        return Mono.justOrEmpty(new WeWorkThirdAuthenticationToken(suiteId, code, loginType, state));
    }

}
